package com.group01.community.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.extension.service.IService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

public class ExcelUtils {
    /**
     * 导出
     *
     * @param tClass    实体类的Class对象
     * @param iService  Service实现类
     * @param resp      响应对象
     * @param sheetName sheet名
     * @param <T>       导出的实体类
     */
    public static <T> void export(Class<T> tClass, IService<T> iService, HttpServletResponse resp, String sheetName) {
        try {
            List<T> list = iService.list();
            //文件名
            String fileName = UUID.randomUUID().toString();
            fileName = fileName.substring(0, fileName.indexOf("-"));
            //设置下载信息
            resp.setContentType("application/vnd.ms-excel");
            resp.setCharacterEncoding("utf-8");
            resp.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //调用方法进行写操作
            EasyExcel.write(resp.getOutputStream(), tClass)
                    .sheet(sheetName)
                    .registerWriteHandler(new SimpleColumnWidthStyleStrategy(15))
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断该对象是否所有属性为空
     *
     * @param object
     * @return
     */
    public static boolean isAllFieldNull(Object object) {
        boolean flag = true;

        Class clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            //设置属性是可以访问的(私有的也可以)
            field.setAccessible(true);
            Object value = null;
            try {
                value = field.get(object);
                // 只要有1个属性不为空,那么就不是所有的属性值都为空
                if (value != null) {
                    flag = false;
                    break;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
}
